// pages/cart/cart.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address:{},
    cart:[],
    checkAll:false,
    totalNum:0,
    totalPrice:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () { 
    const address = wx.getStorageSync('address');
    const cart = wx.getStorageSync('cart')||[];
    this.setData({
      address
    })
    this.setCart(cart)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  address(e){
    wx.chooseAddress({
      success: (result) => {
        wx.setStorageSync('address', result)
      },
    })
  },
  // 商品的选中
  itemCheck(e){
    const id = e.currentTarget.dataset.id;
    let {cart} = this.data;
    let index = cart.findIndex((v)=>v.goods_id === id);
    cart[index].check=!cart[index].check;
    this.setCart(cart);

  },
  setCart(cart){
    let totalNum = 0;
    let totalPrice = 0;
    const checkAll = cart.length && cart.every((e)=>e.check)
    cart.forEach((c)=>{
      if(c.check){
        totalNum+=c.num;
        totalPrice+=c.num*c.goods_price
      }
    });
    this.setData({
      cart,
      totalPrice,
      totalNum,
      checkAll
    });
    wx.setStorageSync('cart', cart);
  },
  allCheck(){
    let {cart,checkAll} = this.data;
    checkAll = !checkAll;
    cart.forEach((v)=>{
      v.check = checkAll
    });
    this.setCart(cart)
  },
  numedit(e){
    const {id,opra} = e.currentTarget.dataset;
    let {cart}  = this.data;
    const index = cart.findIndex(v=>v.goods_id === id);
    if(cart[index].num+opra){
    cart[index].num += opra;
    }else{
      wx.showModal({
        title:'是否在购物车中删除该物品',
        success:(res)=>{
          if(res.confirm){
            cart.splice(index,1);
            this.setCart(cart);
          }
        }
      })
    }
    this.setCart(cart)
  },
  pay(){
    let {address,totalNum}  = this.data;
    if(address.userName){

    }else{
      wx.showToast({
        title: '你还没添加地址信息',
        icon:'none'
      })
      return
    }
    if(totalNum){
      wx.navigateTo({
        url: '/pages/pay/pay',
      })
    }else{
      wx.showToast({
        title: '您还没有选购商品',
        icon:'none'
      })
    }
  }
})